package com.evaluation.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.evaluation.common.Result;
import com.evaluation.entity.*;
import com.evaluation.service.DeptScoreService;
import com.evaluation.service.TeacherScoreService;
import com.evaluation.service.DeptIndicatorsScoreService;
import com.evaluation.service.TeacherIndicatorsScoreService;
import com.evaluation.service.DeptService;
import com.evaluation.service.TeacherService;
import com.evaluation.service.IndicatorsService;
import com.evaluation.service.DeptEvaluatingRelationService;
import com.evaluation.service.TeacherEvaluatingRelationService;
import com.evaluation.service.IndicatorsWfService;
import com.evaluation.util.ExcelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 分数查询管理控制器
 */
@RestController
@RequestMapping("/api/admin/score")
public class AdminScoreController {

    @Autowired
    private DeptScoreService deptScoreService;

    @Autowired
    private TeacherScoreService teacherScoreService;

    @Autowired
    private DeptIndicatorsScoreService deptIndicatorsScoreService;

    @Autowired
    private TeacherIndicatorsScoreService teacherIndicatorsScoreService;

    @Autowired
    private DeptService deptService;

    @Autowired
    private TeacherService teacherService;

    @Autowired
    private IndicatorsService indicatorsService;

    @Autowired
    private DeptEvaluatingRelationService deptRelationService;

    @Autowired
    private TeacherEvaluatingRelationService teacherRelationService;

    @Autowired
    private IndicatorsWfService indicatorsWfService;

    /**
     * 查询部门分数列表
     */
    @GetMapping("/dept/list")
    public Result<Map<String, Object>> getDeptScoresList(@RequestParam(defaultValue = "1") Integer page,
                                    @RequestParam(defaultValue = "10") Integer size,
                                    @RequestParam(required = false) String bcpbm,
                                    @RequestParam(required = false) String scoreRange) {
        try {
            QueryWrapper<DeptScore> queryWrapper = new QueryWrapper<>();

            // 根据部门名称或编号搜索
            if (bcpbm != null && !bcpbm.trim().isEmpty()) {
                // 先根据部门名称查找部门编号
                List<Dept> depts = deptService.list(
                    new QueryWrapper<Dept>().like("BMMC", bcpbm)
                );
                
                if (!depts.isEmpty()) {
                    // 获取所有匹配的部门编号
                    List<String> deptCodes = depts.stream()
                        .map(Dept::getBmbh)
                        .collect(Collectors.toList());
                    
                    // 在部门分数表中搜索这些部门编号
                    queryWrapper.in("BCPBM", deptCodes);
                } else {
                    // 如果没有找到匹配的部门，直接按BCPBM字段搜索（兼容直接输入部门编号的情况）
                    queryWrapper.like("BCPBM", bcpbm);
                }
            }

            // 处理分数范围查询
            if (scoreRange != null && !scoreRange.trim().isEmpty()) {
                String[] range = scoreRange.split("-");
                if (range.length == 2) {
                    double minScore = Double.parseDouble(range[0]);
                    double maxScore = Double.parseDouble(range[1]);
                    queryWrapper.between("SCORE", minScore, maxScore);
                }
            }

            queryWrapper.orderByDesc("SCORE");

            Page<DeptScore> pageResult = deptScoreService.page(new Page<>(page, size), queryWrapper);

            // 转换数据格式，添加部门名称等信息
            List<Map<String, Object>> enrichedList = pageResult.getRecords().stream().map(score -> {
                Map<String, Object> map = new HashMap<>();
                map.put("bh", score.getBh());
                map.put("bcpbm", score.getBcpbm());
                // 格式化分数，保留一位小数
                double formattedScore = Math.round(score.getScore() * 10.0) / 10.0;
                map.put("score", formattedScore);
                map.put("totalScore", formattedScore); // 前端期望的字段名

                // 获取部门信息
                Dept dept = deptService.getOne(new QueryWrapper<Dept>().eq("BMBH", score.getBcpbm()));
                if (dept != null) {
                    map.put("bmbh", dept.getBmbh());
                    map.put("bmmc", dept.getBmmc());
                } else {
                    // 如果按部门编号找不到，尝试按部门名称查找
                    dept = deptService.getOne(new QueryWrapper<Dept>().eq("BMMC", score.getBcpbm()));
                    if (dept != null) {
                        map.put("bmbh", dept.getBmbh());
                        map.put("bmmc", dept.getBmmc());
                    } else {
                        map.put("bmbh", score.getBcpbm());
                        map.put("bmmc", score.getBcpbm());
                    }
                }

                return map;
            }).collect(Collectors.toList());

            // 构造分页结果
            Map<String, Object> result = new HashMap<>();
            result.put("records", enrichedList);
            result.put("total", pageResult.getTotal());
            result.put("size", pageResult.getSize());
            result.put("current", pageResult.getCurrent());
            result.put("pages", pageResult.getPages());

            return Result.success(result);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询部门分数列表失败");
        }
    }

    /**
     * 查询教师分数列表
     */
    @GetMapping("/teacher/list")
    public Result<Map<String, Object>> getTeacherScoresList(@RequestParam(defaultValue = "1") Integer page,
                                       @RequestParam(defaultValue = "10") Integer size,
                                       @RequestParam(required = false) String bcpjs,
                                       @RequestParam(required = false) String scoreRange) {
        try {
            QueryWrapper<TeacherScore> queryWrapper = new QueryWrapper<>();

            // 根据教师姓名或编号搜索
            if (bcpjs != null && !bcpjs.trim().isEmpty()) {
                // 先根据教师姓名查找教师编号
                List<Teacher> teachers = teacherService.list(
                    new QueryWrapper<Teacher>().like("JSXM", bcpjs)
                );
                
                if (!teachers.isEmpty()) {
                    // 获取所有匹配的教师编号
                    List<String> teacherCodes = teachers.stream()
                        .map(t -> String.valueOf(t.getJsbh()))
                        .collect(Collectors.toList());
                    
                    // 在教师分数表中搜索这些教师编号
                    queryWrapper.in("BCPJS", teacherCodes);
                } else {
                    // 如果没有找到匹配的教师，直接按BCPJS字段搜索（兼容直接输入教师编号的情况）
                    queryWrapper.like("BCPJS", bcpjs);
                }
            }

            // 处理分数范围查询
            if (scoreRange != null && !scoreRange.trim().isEmpty()) {
                String[] range = scoreRange.split("-");
                if (range.length == 2) {
                    double minScore = Double.parseDouble(range[0]);
                    double maxScore = Double.parseDouble(range[1]);
                    queryWrapper.between("SCORE", minScore, maxScore);
                }
            }

            queryWrapper.orderByDesc("SCORE");

            Page<TeacherScore> pageResult = teacherScoreService.page(new Page<>(page, size), queryWrapper);

            // 转换数据格式，格式化分数保留一位小数
            List<Map<String, Object>> enrichedList = pageResult.getRecords().stream().map(score -> {
                Map<String, Object> map = new HashMap<>();
                map.put("bh", score.getBh());
                map.put("bcpjs", score.getBcpjs());
                // 格式化分数，保留一位小数
                double formattedScore = Math.round(score.getScore() * 10.0) / 10.0;
                map.put("score", formattedScore);
                map.put("totalScore", formattedScore); // 前端期望的字段名

                // 获取教师信息 - 先尝试按教师编号查找，再尝试按教师姓名查找
                Teacher teacher = teacherService.getOne(new QueryWrapper<Teacher>().eq("JSBH", score.getBcpjs()));
                if (teacher == null) {
                    // 如果按编号找不到，尝试按姓名查找
                    teacher = teacherService.getOne(new QueryWrapper<Teacher>().eq("JSXM", score.getBcpjs()));
                }
                if (teacher == null) {
                    // 如果按姓名也找不到，尝试按工号查找
                    teacher = teacherService.getOne(new QueryWrapper<Teacher>().eq("JSGH", score.getBcpjs()));
                }
                
                if (teacher != null) {
                    map.put("jsbh", teacher.getJsbh()); // 教师编号
                    map.put("jsxm", teacher.getJsxm()); // 教师姓名
                    map.put("bmbh", teacher.getBmbh()); // 部门编号
                    
                    // 获取部门名称
                    Dept dept = deptService.getOne(new QueryWrapper<Dept>().eq("BMBH", teacher.getBmbh()));
                    map.put("bmmc", dept != null ? dept.getBmmc() : "");
                } else {
                    map.put("jsbh", score.getBcpjs());
                    map.put("jsxm", score.getBcpjs()); // 如果找不到教师信息，显示原始值
                    map.put("bmbh", "");
                    map.put("bmmc", "");
                }

                return map;
            }).collect(Collectors.toList());

            Map<String, Object> data = new HashMap<>();
            data.put("list", enrichedList);
            data.put("records", enrichedList); // 兼容不同的前端期望
            data.put("total", pageResult.getTotal());
            data.put("page", page);
            data.put("size", size);

            return Result.success(data);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询教师分数列表失败");
        }
    }

    /**
     * 获取教师总分列表（分页）
     */
    @GetMapping("/teacher-total-scores")
    public Result<Map<String, Object>> getTeacherTotalScores(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String teacherName,
            @RequestParam(required = false) String deptName,
            @RequestParam(required = false) String scoreRange) {

        try {
            Page<TeacherScore> pageParam = new Page<>(page, size);
            QueryWrapper<TeacherScore> queryWrapper = new QueryWrapper<>();

            // 根据教师姓名搜索
            if (teacherName != null && !teacherName.trim().isEmpty()) {
                // 先根据教师姓名查找教师编号
                List<Teacher> teachers = teacherService.list(
                    new QueryWrapper<Teacher>().like("JSXM", teacherName)
                );
                
                if (!teachers.isEmpty()) {
                    // 获取所有匹配的教师编号
                    List<String> teacherCodes = teachers.stream()
                        .map(t -> String.valueOf(t.getJsbh()))
                        .collect(Collectors.toList());
                    
                    // 在教师分数表中搜索这些教师编号
                    queryWrapper.in("BCPJS", teacherCodes);
                } else {
                    // 如果没有找到匹配的教师，直接按BCPJS字段搜索（兼容直接输入教师编号的情况）
                    queryWrapper.like("BCPJS", teacherName);
                }
            }

            // 根据部门搜索
            if (deptName != null && !deptName.trim().isEmpty()) {
                // 先根据部门名称或部门编号查找部门
                List<Dept> depts = deptService.list(
                    new QueryWrapper<Dept>()
                        .like("BMMC", deptName)
                        .or()
                        .eq("BMBH", deptName)
                );
                
                if (!depts.isEmpty()) {
                    // 获取所有匹配的部门编号
                    List<String> deptCodes = depts.stream()
                        .map(Dept::getBmbh)
                        .collect(Collectors.toList());
                    
                    // 根据部门编号查找教师
                    List<Teacher> teachersInDept = teacherService.list(
                        new QueryWrapper<Teacher>().in("BMBH", deptCodes)
                    );
                    
                    if (!teachersInDept.isEmpty()) {
                        // 获取这些教师的编号和姓名
                        List<String> teacherIdentifiers = new ArrayList<>();
                        for (Teacher t : teachersInDept) {
                            teacherIdentifiers.add(String.valueOf(t.getJsbh()));
                            teacherIdentifiers.add(t.getJsxm());
                        }
                        
                        // 在教师分数表中搜索这些教师
                        queryWrapper.in("BCPJS", teacherIdentifiers);
                    } else {
                        // 如果没有找到匹配的教师，返回空结果
                        queryWrapper.eq("BCPJS", "NO_MATCH_FOUND");
                    }
                } else {
                    // 如果没有找到匹配的部门，返回空结果
                    queryWrapper.eq("BCPJS", "NO_MATCH_FOUND");
                }
            }

            // 处理分数范围查询
            if (scoreRange != null && !scoreRange.trim().isEmpty()) {
                String[] range = scoreRange.split("-");
                if (range.length == 2) {
                    double minScore = Double.parseDouble(range[0]);
                    double maxScore = Double.parseDouble(range[1]);
                    queryWrapper.between("SCORE", minScore, maxScore);
                }
            }

            queryWrapper.orderByDesc("SCORE");

            Page<TeacherScore> pageResult = teacherScoreService.page(pageParam, queryWrapper);

            List<Map<String, Object>> enrichedList = pageResult.getRecords().stream().map(score -> {
                Map<String, Object> map = new HashMap<>();
                map.put("bh", score.getBh());
                map.put("bcpjs", score.getBcpjs());
                // 格式化分数，保留一位小数
                double formattedScore = Math.round(score.getScore() * 10.0) / 10.0;
                map.put("score", formattedScore);
                map.put("totalScore", formattedScore); // 前端期望的字段名

                // 获取教师信息 - 先尝试按教师编号查找，再尝试按教师姓名查找
                Teacher teacher = teacherService.getOne(new QueryWrapper<Teacher>().eq("JSBH", score.getBcpjs()));
                if (teacher == null) {
                    // 如果按编号找不到，尝试按姓名查找
                    teacher = teacherService.getOne(new QueryWrapper<Teacher>().eq("JSXM", score.getBcpjs()));
                }
                if (teacher == null) {
                    // 如果按姓名也找不到，尝试按工号查找
                    teacher = teacherService.getOne(new QueryWrapper<Teacher>().eq("JSGH", score.getBcpjs()));
                }
                
                if (teacher != null) {
                    map.put("jsbh", teacher.getJsbh()); // 教师编号
                    map.put("jsxm", teacher.getJsxm()); // 教师姓名
                    map.put("bmbh", teacher.getBmbh()); // 部门编号
                    
                    // 获取部门名称
                    Dept dept = deptService.getOne(new QueryWrapper<Dept>().eq("BMBH", teacher.getBmbh()));
                    map.put("bmmc", dept != null ? dept.getBmmc() : "");
                } else {
                    map.put("jsbh", score.getBcpjs());
                    map.put("jsxm", score.getBcpjs()); // 如果找不到教师信息，显示原始值
                    map.put("bmbh", "");
                    map.put("bmmc", "");
                }

                return map;
            }).collect(Collectors.toList());

            Map<String, Object> data = new HashMap<>();
            data.put("list", enrichedList);
            data.put("records", enrichedList); // 兼容不同的前端期望
            data.put("total", pageResult.getTotal());
            data.put("page", page);
            data.put("size", size);

            return Result.success(data);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取教师总分失败");
        }
    }

    /**
     * 查询部门指标分数
     */
    @GetMapping("/dept/indicators/{bcpbm}")
    public Result<List<DeptIndicatorsScore>> getDeptIndicatorsScores(@PathVariable String bcpbm) {
        try {
            QueryWrapper<DeptIndicatorsScore> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("BCPBM", bcpbm);
            queryWrapper.orderByAsc("CPZBBH");

            return Result.success(deptIndicatorsScoreService.list(queryWrapper));
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询部门指标分数失败");
        }
    }

    /**
     * 获取部门指标分数列表（分页）
     */
    @GetMapping("/dept-indicator-scores")
    public Result<Map<String, Object>> getDeptIndicatorScores(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String deptName,
            @RequestParam(required = false) String indicatorId) {

        try {
            Page<DeptIndicatorsScore> pageParam = new Page<>(page, size);
            QueryWrapper<DeptIndicatorsScore> queryWrapper = new QueryWrapper<>();

            // 根据部门名称搜索
            if (deptName != null && !deptName.trim().isEmpty()) {
                // 先根据部门名称查找部门编号
                List<Dept> depts = deptService.list(
                    new QueryWrapper<Dept>().like("BMMC", deptName)
                );
                
                if (!depts.isEmpty()) {
                    // 获取所有匹配的部门编号
                    List<String> deptCodes = depts.stream()
                        .map(Dept::getBmbh)
                        .collect(Collectors.toList());
                    
                    // 在部门指标分数表中搜索这些部门编号
                    queryWrapper.in("BCPBM", deptCodes);
                } else {
                    // 如果没有找到匹配的部门，直接按BCPBM字段搜索（兼容直接输入部门编号的情况）
                    queryWrapper.like("BCPBM", deptName);
                }
            }
            if (indicatorId != null && !indicatorId.trim().isEmpty()) {
                queryWrapper.eq("CPZBBH", indicatorId);
            }

            queryWrapper.orderByDesc("BH");

            Page<DeptIndicatorsScore> pageResult = deptIndicatorsScoreService.page(pageParam, queryWrapper);

            List<Map<String, Object>> enrichedList = pageResult.getRecords().stream().map(score -> {
                Map<String, Object> map = new HashMap<>();
                map.put("bh", score.getBh());
                map.put("bcpbm", score.getBcpbm());
                map.put("cpzbbh", score.getCpzbbh());
                map.put("cpqzbh", score.getCpqzbh()); // 测评权重编号
                map.put("score", score.getScore());

                // 获取部门信息
                Dept dept = deptService.getOne(new QueryWrapper<Dept>().eq("BMBH", score.getBcpbm()));
                if (dept != null) {
                    map.put("bmbh", dept.getBmbh()); // 部门编号
                    map.put("bmmc", dept.getBmmc()); // 部门名称
                } else {
                    // 如果按部门编号找不到，尝试按部门名称查找
                    dept = deptService.getOne(new QueryWrapper<Dept>().eq("BMMC", score.getBcpbm()));
                    if (dept != null) {
                        map.put("bmbh", dept.getBmbh());
                        map.put("bmmc", dept.getBmmc());
                    } else {
                        map.put("bmbh", score.getBcpbm());
                        map.put("bmmc", score.getBcpbm());
                    }
                }

                // 获取指标信息
                Indicators indicator = indicatorsService.getOne(new QueryWrapper<Indicators>().eq("ZBBH", score.getCpzbbh()));
                if (indicator != null) {
                    map.put("zbbh", indicator.getZbbh()); // 指标编号
                    map.put("zbmc", indicator.getZbmc()); // 指标名称
                } else {
                    map.put("zbbh", score.getCpzbbh());
                    map.put("zbmc", "");
                }

                // 获取测评权重信息
                IndicatorsWf indicatorsWf = indicatorsWfService.getOne(new QueryWrapper<IndicatorsWf>().eq("QZBH", score.getCpqzbh()));
                if (indicatorsWf != null) {
                    map.put("cpqzmc", indicatorsWf.getQzmc()); // 测评权重名称
                    map.put("cpzbqz", indicatorsWf.getQz()); // 测评指标权重
                } else {
                    map.put("cpqzmc", "");
                    map.put("cpzbqz", score.getCpzbqz()); // 如果找不到权重信息，使用原有的权重值
                }

                return map;
            }).collect(Collectors.toList());

            Map<String, Object> data = new HashMap<>();
            data.put("list", enrichedList);
            data.put("total", pageResult.getTotal());
            data.put("page", page);
            data.put("size", size);

            return Result.success(data);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取部门指标分数失败");
        }
    }

    /**
     * 获取部门指标分数详情
     */
    @GetMapping("/dept-indicator-scores/{bh}")
    public Result<Map<String, Object>> getDeptIndicatorScoreDetail(@PathVariable String bh) {
        try {
            DeptIndicatorsScore score = deptIndicatorsScoreService.getById(bh);
            if (score == null) {
                return Result.error("部门指标分数不存在");
            }

            Map<String, Object> detail = new HashMap<>();
            detail.put("bh", score.getBh());
            detail.put("bcpbm", score.getBcpbm());
            detail.put("cpzbbh", score.getCpzbbh());
            detail.put("cpzbqz", score.getCpzbqz());
            detail.put("score", score.getScore());

            // 获取部门信息
            Dept dept = deptService.getOne(new QueryWrapper<Dept>().eq("BMBH", score.getBcpbm()));
            if (dept != null) {
                detail.put("bmbh", dept.getBmbh());
                detail.put("bmmc", dept.getBmmc());
            } else {
                detail.put("bmbh", score.getBcpbm());
                detail.put("bmmc", score.getBcpbm());
            }

            // 获取指标信息
            Indicators indicator = indicatorsService.getOne(new QueryWrapper<Indicators>().eq("ZBBH", score.getCpzbbh()));
            if (indicator != null) {
                detail.put("zbmc", indicator.getZbmc());
            } else {
                detail.put("zbmc", "");
            }

            // 获取测评明细（从部门测评关系表）
            QueryWrapper<DeptEvaluatingRelation> relationQuery = new QueryWrapper<>();
            relationQuery.eq("BCPBM", score.getBcpbm());
            relationQuery.eq("CPZBBH", score.getCpzbbh());
            relationQuery.eq("CPBS", "1");
            List<DeptEvaluatingRelation> relations = deptRelationService.list(relationQuery);

            List<Map<String, Object>> evaluationDetails = relations.stream().map(relation -> {
                Map<String, Object> evalDetail = new HashMap<>();
                evalDetail.put("cprbm", relation.getCpjs()); // 测评教师
                evalDetail.put("cprxm", relation.getCpjs()); // 测评教师姓名（这里可能需要关联教师表获取真实姓名）
                evalDetail.put("totalscore", relation.getTotalscore());
                evalDetail.put("cprq", relation.getCpsj()); // 测评时间
                return evalDetail;
            }).collect(Collectors.toList());

            detail.put("evaluationDetails", evaluationDetails);

            return Result.success(detail);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取部门指标分数详情失败");
        }
    }

    /**
     * 获取部门指标分数详情（按部门编号）
     */
    @GetMapping("/dept-indicator-scores/detail/{deptCode}")
    public Result<List<Map<String, Object>>> getDeptIndicatorScoresByDept(@PathVariable String deptCode) {
        try {
            QueryWrapper<DeptIndicatorsScore> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("BCPBM", deptCode);
            queryWrapper.orderByAsc("CPZBBH");

            List<DeptIndicatorsScore> scores = deptIndicatorsScoreService.list(queryWrapper);
            
            List<Map<String, Object>> enrichedList = scores.stream().map(score -> {
                Map<String, Object> map = new HashMap<>();
                map.put("bh", score.getBh());
                map.put("bcpbm", score.getBcpbm());
                map.put("cpzbbh", score.getCpzbbh());
                map.put("cpzbqz", score.getCpzbqz());
                map.put("score", score.getScore());

                // 获取指标信息
                Indicators indicator = indicatorsService.getOne(new QueryWrapper<Indicators>().eq("ZBBH", score.getCpzbbh()));
                if (indicator != null) {
                    map.put("zbbh", indicator.getZbbh());
                    map.put("zbmc", indicator.getZbmc());
                    map.put("indicatorCode", indicator.getZbbh());
                    map.put("indicatorName", indicator.getZbmc());
                    map.put("pointCode", score.getCpzbbh());
                    map.put("pointName", indicator.getZbmc());
                    map.put("maxScore", 100); // 假设满分为100
                    map.put("totalScore", 100);
                } else {
                    map.put("zbbh", score.getCpzbbh());
                    map.put("zbmc", "");
                    map.put("indicatorCode", score.getCpzbbh());
                    map.put("indicatorName", "");
                    map.put("pointCode", score.getCpzbbh());
                    map.put("pointName", "");
                    map.put("maxScore", 100);
                    map.put("totalScore", 100);
                }

                map.put("qz", score.getCpzbqz());
                map.put("weight", score.getCpzbqz());

                return map;
            }).collect(Collectors.toList());

            return Result.success(enrichedList);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取部门指标分数详情失败");
        }
    }

    /**
     * 查询教师指标分数
     */
    @GetMapping("/teacher/indicators/{bcpjs}")
    public Result<List<TeacherIndicatorsScore>> getTeacherIndicatorsScores(@PathVariable String bcpjs) {
        try {
            QueryWrapper<TeacherIndicatorsScore> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("BCPJS", bcpjs);
            queryWrapper.orderByAsc("CPZBBH");

            return Result.success(teacherIndicatorsScoreService.list(queryWrapper));
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询教师指标分数失败");
        }
    }

    /**
     * 获取教师指标分数列表（分页）
     */
    @GetMapping("/teacher-indicator-scores")
    public Result<Map<String, Object>> getTeacherIndicatorScores(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String teacherName,
            @RequestParam(required = false) String indicatorId) {

        try {
            Page<TeacherIndicatorsScore> pageParam = new Page<>(page, size);
            QueryWrapper<TeacherIndicatorsScore> queryWrapper = new QueryWrapper<>();

            // 根据教师姓名搜索
            if (teacherName != null && !teacherName.trim().isEmpty()) {
                // 先根据教师姓名查找教师编号
                List<Teacher> teachers = teacherService.list(
                    new QueryWrapper<Teacher>().like("JSXM", teacherName)
                );
                
                if (!teachers.isEmpty()) {
                    // 获取所有匹配的教师编号
                    List<String> teacherCodes = teachers.stream()
                        .map(t -> String.valueOf(t.getJsbh()))
                        .collect(Collectors.toList());
                    
                    // 在教师指标分数表中搜索这些教师编号
                    queryWrapper.in("BCPJS", teacherCodes);
                } else {
                    // 如果没有找到匹配的教师，直接按BCPJS字段搜索（兼容直接输入教师编号的情况）
                    queryWrapper.like("BCPJS", teacherName);
                }
            }
            if (indicatorId != null && !indicatorId.trim().isEmpty()) {
                queryWrapper.eq("CPZBBH", indicatorId);
            }

            queryWrapper.orderByDesc("BH");

            Page<TeacherIndicatorsScore> pageResult = teacherIndicatorsScoreService.page(pageParam, queryWrapper);

            List<Map<String, Object>> enrichedList = pageResult.getRecords().stream().map(score -> {
                Map<String, Object> map = new HashMap<>();
                map.put("bh", score.getBh());
                map.put("bcpjs", score.getBcpjs());
                map.put("cpzbbh", score.getCpzbbh());
                map.put("cpqzbh", score.getCpqzbh()); // 测评权重编号
                map.put("score", score.getScore());

                // 获取教师信息 - 先尝试按教师编号查找，再尝试按教师姓名查找
                Teacher teacher = teacherService.getOne(new QueryWrapper<Teacher>().eq("JSBH", score.getBcpjs()));
                if (teacher == null) {
                    // 如果按编号找不到，尝试按姓名查找
                    teacher = teacherService.getOne(new QueryWrapper<Teacher>().eq("JSXM", score.getBcpjs()));
                }
                if (teacher == null) {
                    // 如果按姓名也找不到，尝试按工号查找
                    teacher = teacherService.getOne(new QueryWrapper<Teacher>().eq("JSGH", score.getBcpjs()));
                }
                
                if (teacher != null) {
                    map.put("jsbh", teacher.getJsbh()); // 教师编号
                    map.put("jsgh", teacher.getJsgh()); // 教师工号
                    map.put("jsxm", teacher.getJsxm()); // 教师姓名
                    map.put("bmbh", teacher.getBmbh()); // 部门编号
                } else {
                    map.put("jsbh", score.getBcpjs());
                    map.put("jsgh", ""); // 教师工号
                    map.put("jsxm", score.getBcpjs()); // 如果找不到教师信息，显示原始值
                    map.put("bmbh", "");
                }

                // 获取指标信息
                Indicators indicator = indicatorsService.getOne(new QueryWrapper<Indicators>().eq("ZBBH", score.getCpzbbh()));
                if (indicator != null) {
                    map.put("zbbh", indicator.getZbbh()); // 指标编号
                    map.put("zbmc", indicator.getZbmc()); // 指标名称
                } else {
                    map.put("zbbh", score.getCpzbbh());
                    map.put("zbmc", "");
                }

                // 获取测评权重信息
                IndicatorsWf indicatorsWf = indicatorsWfService.getOne(new QueryWrapper<IndicatorsWf>().eq("QZBH", score.getCpqzbh()));
                if (indicatorsWf != null) {
                    map.put("cpqzmc", indicatorsWf.getQzmc()); // 测评权重名称
                    map.put("cpzbqz", indicatorsWf.getQz()); // 测评指标权重
                } else {
                    map.put("cpqzmc", "");
                    map.put("cpzbqz", score.getCpzbqz()); // 如果找不到权重信息，使用原有的权重值
                }

                return map;
            }).collect(Collectors.toList());

            Map<String, Object> data = new HashMap<>();
            data.put("list", enrichedList);
            data.put("total", pageResult.getTotal());
            data.put("page", page);
            data.put("size", size);

            return Result.success(data);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取教师指标分数失败");
        }
    }

    /**
     * 计算部门分数
     */
    @PostMapping("/dept/calculate")
    public Result<String> calculateDeptScores() {
        try {
            // 清空现有分数数据
            deptScoreService.remove(new QueryWrapper<>());
            deptIndicatorsScoreService.remove(new QueryWrapper<>());

            int indicatorCount = 0;
            int totalCount = 0;

            // 1. 计算部门指标分数
            List<Dept> depts = deptService.list(new QueryWrapper<Dept>().eq("BMZT", "0"));
            List<Indicators> indicators = indicatorsService.list(new QueryWrapper<Indicators>().eq("KHFS", "1"));

            for (Dept dept : depts) {
                for (Indicators indicator : indicators) {
                    QueryWrapper<DeptEvaluatingRelation> relationQuery = new QueryWrapper<>();
                    relationQuery.eq("BCPBMBH", dept.getBmbh());
                    relationQuery.eq("CPZBBH", indicator.getZbbh());
                    relationQuery.eq("CPBS", "1");

                    List<DeptEvaluatingRelation> relations = deptRelationService.list(relationQuery);

                    if (!relations.isEmpty()) {
                        // 从relations中获取测评权重编号(cpqzbh)
                        String cpqzbh = relations.get(0).getCpqzbh(); // 取第一个关系记录的权重编号
                        
                        // 根据测评权重编号采用不同的去极值策略计算平均分
                        double avgScore = calculateAverageScoreWithOutlierRemoval(relations, cpqzbh);
                        
                        // 根据测评权重编号从考核指标权重表中读取权重
                        Double qz = 1.0; // 默认权重为1.0
                        if (cpqzbh != null && !cpqzbh.trim().isEmpty()) {
                            IndicatorsWf indicatorsWf = indicatorsWfService.getOne(
                                new QueryWrapper<IndicatorsWf>().eq("QZBH", cpqzbh)
                            );
                            if (indicatorsWf != null && indicatorsWf.getQz() != null) {
                                qz = indicatorsWf.getQz();
                            }
                        }

                        DeptIndicatorsScore score = new DeptIndicatorsScore();
                        score.setBh(generateDeptIndicatorScoreId());
                        score.setBcpbm(dept.getBmbh());
                        score.setCpzbbh(indicator.getZbbh());
                        score.setCpzbqz(qz); // 设置从权重表读取的权重值
                        score.setCpqzbh(cpqzbh); // 设置测评权重编号
                        score.setScore((int) Math.round(avgScore));

                        deptIndicatorsScoreService.save(score);
                        indicatorCount++;
                    }
                }
            }

            // 2. 计算部门总分 - 使用权重乘以分数的求和方式
            for (Dept dept : depts) {
                QueryWrapper<DeptIndicatorsScore> scoreQuery = new QueryWrapper<>();
                scoreQuery.eq("BCPBM", dept.getBmbh());

                List<DeptIndicatorsScore> indicatorScores = deptIndicatorsScoreService.list(scoreQuery);

                if (!indicatorScores.isEmpty()) {
                    // 计算权重乘以分数的总和：sum(CPZBQZ * SCORE)
                    double totalScore = indicatorScores.stream()
                            .filter(s -> s.getScore() != null && s.getCpzbqz() != null)
                            .mapToDouble(s -> s.getCpzbqz() * s.getScore())
                            .sum();

                    DeptScore score = new DeptScore();
                    score.setBh(generateDeptScoreId());
                    score.setBcpbm(dept.getBmbh());
                    score.setScore(totalScore);

                    deptScoreService.save(score);
                    totalCount++;
                }
            }

            return Result.success("部门分数计算完成，指标分数：" + indicatorCount + "条，总分：" + totalCount + "条");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("计算部门分数失败");
        }
    }

    /**
     * 计算教师分数
     */
    @PostMapping("/teacher/calculate")
    public Result<String> calculateTeacherScores() {
        try {
            // 清空现有分数数据
            teacherScoreService.remove(new QueryWrapper<>());
            teacherIndicatorsScoreService.remove(new QueryWrapper<>());

            int indicatorCount = 0;
            int totalCount = 0;

            // 1. 根据被测评教师（BCPJS）、测评指标编号（CPZBBH）和测评权重编号（CPQZBH）对测评关系表数据进行分组
            // 获取所有已测评的教师测评关系数据
            QueryWrapper<TeacherEvaluatingRelation> relationQuery = new QueryWrapper<>();
            relationQuery.eq("CPBS", "1"); // 已测评
            relationQuery.isNotNull("TOTALSCORE"); // 有分数
            relationQuery.gt("TOTALSCORE", 0); // 分数大于0
            List<TeacherEvaluatingRelation> allRelations = teacherRelationService.list(relationQuery);

            // 按 BCPJS, CPZBBH, CPQZBH 分组并计算平均分
            Map<String, List<TeacherEvaluatingRelation>> groupedRelations = allRelations.stream()
                    .collect(Collectors.groupingBy(relation -> 
                        relation.getBcpjs() + "|" + relation.getCpzbbh() + "|" + relation.getCpqzbh()
                    ));

            // 处理每个分组
            for (Map.Entry<String, List<TeacherEvaluatingRelation>> entry : groupedRelations.entrySet()) {
                String[] keys = entry.getKey().split("\\|");
                String bcpjs = keys[0];
                String cpzbbh = keys[1];
                String cpqzbh = keys[2];
                
                List<TeacherEvaluatingRelation> relations = entry.getValue();
                
                // 计算该分组的平均分
                double avgScore = relations.stream()
                        .filter(r -> r.getTotalscore() != null && r.getTotalscore() > 0)
                        .mapToInt(TeacherEvaluatingRelation::getTotalscore)
                        .average()
                        .orElse(0.0);

                // 根据测评权重编号从考核指标权重表中读取权重
                Double qz = 1.0; // 默认权重为1.0
                if (cpqzbh != null && !cpqzbh.trim().isEmpty()) {
                    IndicatorsWf indicatorsWf = indicatorsWfService.getOne(
                        new QueryWrapper<IndicatorsWf>().eq("QZBH", cpqzbh)
                    );
                    if (indicatorsWf != null && indicatorsWf.getQz() != null) {
                        qz = indicatorsWf.getQz();
                    }
                }

                // 查找对应的教师信息，确保使用教师编号作为标识
                Teacher teacher = teacherService.getOne(new QueryWrapper<Teacher>().eq("JSBH", bcpjs));
                if (teacher == null) {
                    teacher = teacherService.getOne(new QueryWrapper<Teacher>().eq("JSXM", bcpjs));
                }
                if (teacher == null) {
                    teacher = teacherService.getOne(new QueryWrapper<Teacher>().eq("JSGH", bcpjs));
                }
                
                String teacherCode = teacher != null ? String.valueOf(teacher.getJsbh()) : bcpjs;

                // 创建教师指标分数记录
                TeacherIndicatorsScore score = new TeacherIndicatorsScore();
                score.setBh(generateTeacherIndicatorScoreId());
                score.setBcpjs(teacherCode); // 使用教师编号作为标识
                score.setCpzbbh(cpzbbh); // 测评指标编号
                score.setCpzbqz(qz); // 测评指标权重
                score.setCpqzbh(cpqzbh); // 测评权重编号
                score.setScore((int) Math.round(avgScore)); // 平均分

                teacherIndicatorsScoreService.save(score);
                indicatorCount++;
            }

            // 2. 计算教师总分 - 使用权重乘以分数的求和方式
            // 获取所有有指标分数的教师
            List<String> teachersWithScores = teacherIndicatorsScoreService.list()
                    .stream()
                    .map(TeacherIndicatorsScore::getBcpjs)
                    .distinct()
                    .collect(Collectors.toList());

            for (String teacherCode : teachersWithScores) {
                QueryWrapper<TeacherIndicatorsScore> scoreQuery = new QueryWrapper<>();
                scoreQuery.eq("BCPJS", teacherCode);

                List<TeacherIndicatorsScore> indicatorScores = teacherIndicatorsScoreService.list(scoreQuery);

                if (!indicatorScores.isEmpty()) {
                    // 计算权重乘以分数的总和：sum(CPZBQZ * SCORE)
                    double totalScore = indicatorScores.stream()
                            .filter(s -> s.getScore() != null && s.getCpzbqz() != null)
                            .mapToDouble(s -> s.getCpzbqz() * s.getScore())
                            .sum();

                    TeacherScore score = new TeacherScore();
                    score.setBh(generateTeacherScoreId());
                    score.setBcpjs(teacherCode);
                    score.setScore(totalScore);

                    teacherScoreService.save(score);
                    totalCount++;
                }
            }

            return Result.success("教师分数计算完成，指标分数：" + indicatorCount + "条，总分：" + totalCount + "条");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("计算教师分数失败：" + e.getMessage());
        }
    }

    /**
     * 导出部门总分
     */
    @GetMapping("/export/dept-total-scores")
    public void exportDeptTotalScores(HttpServletResponse response) {
        try {
            List<DeptScore> list = deptScoreService.list(new QueryWrapper<DeptScore>().orderByDesc("SCORE"));
            List<Map<String, Object>> exportData = new ArrayList<>();

            for (DeptScore score : list) {
                Map<String, Object> map = new HashMap<>();
                map.put("编号", score.getBh());
                map.put("部门编号", score.getBcpbm());
                map.put("总分", score.getScore());

                // 获取部门信息
                Dept dept = deptService.getOne(new QueryWrapper<Dept>().eq("BMBH", score.getBcpbm()));
                if (dept != null) {
                    map.put("部门名称", dept.getBmmc());
                } else {
                    // 如果按部门编号找不到，尝试按部门名称查找
                    dept = deptService.getOne(new QueryWrapper<Dept>().eq("BMMC", score.getBcpbm()));
                    map.put("部门名称", dept != null ? dept.getBmmc() : score.getBcpbm());
                }

                exportData.add(map);
            }

            if (!exportData.isEmpty()) {
                ExcelUtil.exportExcel(response, "部门总分", exportData);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 导出部门分数
     */
    @GetMapping("/dept/export")
    public void exportDeptScores(HttpServletResponse response) {
        try {
            List<DeptScore> list = deptScoreService.list(new QueryWrapper<DeptScore>().orderByDesc("SCORE"));
            List<Map<String, Object>> exportData = new ArrayList<>();

            for (DeptScore score : list) {
                Map<String, Object> map = new HashMap<>();
                map.put("编号", score.getBh());
                map.put("部门编号", score.getBcpbm());
                map.put("总分", score.getScore());

                Dept dept = deptService.getOne(new QueryWrapper<Dept>().eq("BMBH", score.getBcpbm()));
                map.put("部门名称", dept != null ? dept.getBmmc() : "");

                exportData.add(map);
            }

            if (!exportData.isEmpty()) {
                ExcelUtil.exportExcel(response, "部门分数", exportData);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 导出部门指标分数
     */
    @GetMapping("/export/dept-indicator-scores")
    public void exportDeptIndicatorScores(HttpServletResponse response) {
        try {
            List<DeptIndicatorsScore> list = deptIndicatorsScoreService.list(new QueryWrapper<DeptIndicatorsScore>().orderByDesc("BH"));
            List<Map<String, Object>> exportData = new ArrayList<>();

            for (DeptIndicatorsScore score : list) {
                // 使用LinkedHashMap保证字段顺序
                Map<String, Object> map = new LinkedHashMap<>();
                
                // 1. 部门编号
                map.put("部门编号", score.getBcpbm() != null ? score.getBcpbm() : "");
                
                // 2. 部门名称
                Dept dept = deptService.getOne(new QueryWrapper<Dept>().eq("BMBH", score.getBcpbm()));
                if (dept != null) {
                    map.put("部门名称", dept.getBmmc() != null ? dept.getBmmc() : "");
                } else {
                    // 如果按部门编号找不到，尝试按部门名称查找
                    dept = deptService.getOne(new QueryWrapper<Dept>().eq("BMMC", score.getBcpbm()));
                    map.put("部门名称", dept != null && dept.getBmmc() != null ? dept.getBmmc() : (score.getBcpbm() != null ? score.getBcpbm() : ""));
                }
                
                // 3. 指标编号
                map.put("指标编号", score.getCpzbbh() != null ? score.getCpzbbh() : "");
                
                // 4. 测评权重编号
                map.put("测评权重编号", score.getCpqzbh() != null ? score.getCpqzbh() : "");
                
                // 5. 测评权重名称
                IndicatorsWf indicatorsWf = null;
                if (score.getCpqzbh() != null && !score.getCpqzbh().trim().isEmpty()) {
                    indicatorsWf = indicatorsWfService.getOne(new QueryWrapper<IndicatorsWf>().eq("QZBH", score.getCpqzbh()));
                }
                if (indicatorsWf != null && indicatorsWf.getQzmc() != null) {
                    map.put("测评权重名称", indicatorsWf.getQzmc());
                } else {
                    map.put("测评权重名称", "");
                }
                
                // 6. 测评指标权重
                map.put("测评指标权重", score.getCpzbqz() != null ? score.getCpzbqz() : "");
                
                // 7. 分数
                map.put("分数", score.getScore() != null ? score.getScore() : "");

                exportData.add(map);
            }

            if (!exportData.isEmpty()) {
                ExcelUtil.exportExcel(response, "部门指标分数", exportData);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 导出部门人事数据
     */
    @GetMapping("/export/dept-personnel-data")
    public void exportDeptPersonnelData(HttpServletResponse response) {
        try {
            // 查询所有部门的指标分数
            List<DeptIndicatorsScore> allScores = deptIndicatorsScoreService.list(
                new QueryWrapper<DeptIndicatorsScore>().orderByAsc("BCPBM", "CPQZBH")
            );
            
            // 按部门分组
            Map<String, List<DeptIndicatorsScore>> deptScoresMap = allScores.stream()
                .collect(Collectors.groupingBy(DeptIndicatorsScore::getBcpbm));
            
            List<Map<String, Object>> exportData = new ArrayList<>();
            
            // 处理每个部门
            for (Map.Entry<String, List<DeptIndicatorsScore>> entry : deptScoresMap.entrySet()) {
                String deptCode = entry.getKey();
                List<DeptIndicatorsScore> scores = entry.getValue();
                
                // 获取部门信息
                Dept dept = deptService.getOne(new QueryWrapper<Dept>().eq("BMBH", deptCode));
                if (dept == null) {
                    // 如果按部门编号找不到，尝试按部门名称查找
                    dept = deptService.getOne(new QueryWrapper<Dept>().eq("BMMC", deptCode));
                }
                
                // 创建导出数据行
                Map<String, Object> row = new LinkedHashMap<>();
                
                // 1. 被测评部门编号
                row.put("被测评部门编号", deptCode);
                
                // 2. 被测评部门
                row.put("被测评部门", dept != null && dept.getBmmc() != null ? dept.getBmmc() : deptCode);
                
                // 初始化各权重编号的数据
                Map<String, IndicatorsWf> weightInfoMap = new HashMap<>();
                Map<String, Double> weightMap = new HashMap<>();
                Map<String, List<Integer>> scoreListMap = new HashMap<>();
                
                // 遍历该部门的所有指标分数，按权重编号分组
                for (DeptIndicatorsScore score : scores) {
                    String qzbh = score.getCpqzbh();
                    if (qzbh != null && (qzbh.equals("4") || qzbh.equals("5") || qzbh.equals("6") || qzbh.equals("7"))) {
                        // 获取权重信息
                        if (!weightInfoMap.containsKey(qzbh)) {
                            IndicatorsWf indicatorsWf = indicatorsWfService.getOne(
                                new QueryWrapper<IndicatorsWf>().eq("QZBH", qzbh)
                            );
                            if (indicatorsWf != null) {
                                weightInfoMap.put(qzbh, indicatorsWf);
                                weightMap.put(qzbh, indicatorsWf.getQz() != null ? indicatorsWf.getQz() : 0.0);
                            } else {
                                // 如果找不到权重信息，使用分数记录中的权重
                                weightMap.put(qzbh, score.getCpzbqz() != null ? score.getCpzbqz() : 0.0);
                            }
                        }
                        // 收集分数（用于后续计算平均值）
                        if (score.getScore() != null) {
                            scoreListMap.computeIfAbsent(qzbh, k -> new ArrayList<>()).add(score.getScore());
                        }
                    }
                }
                
                // 计算每个权重编号的平均分数
                Map<String, Integer> scoreMap = new HashMap<>();
                for (Map.Entry<String, List<Integer>> scoreEntry : scoreListMap.entrySet()) {
                    String qzbh = scoreEntry.getKey();
                    List<Integer> scoreList = scoreEntry.getValue();
                    if (!scoreList.isEmpty()) {
                        double avgScore = scoreList.stream().mapToInt(Integer::intValue).average().orElse(0.0);
                        scoreMap.put(qzbh, (int) Math.round(avgScore));
                    }
                }
                
                // 填充权重编号4的数据
                IndicatorsWf wf4 = weightInfoMap.get("4");
                row.put("权重编号为4的权重名称", wf4 != null && wf4.getQzmc() != null ? wf4.getQzmc() : "");
                row.put("权重编号为4的权重", weightMap.getOrDefault("4", 0.0));
                row.put("权重编号为4的权重得分", scoreMap.getOrDefault("4", 0));
                
                // 填充权重编号5的数据
                IndicatorsWf wf5 = weightInfoMap.get("5");
                row.put("权重编号为5的权重名称", wf5 != null && wf5.getQzmc() != null ? wf5.getQzmc() : "");
                row.put("权重编号为5的权重", weightMap.getOrDefault("5", 0.0));
                row.put("权重编号为5的权重得分", scoreMap.getOrDefault("5", 0));
                
                // 填充权重编号6的数据
                IndicatorsWf wf6 = weightInfoMap.get("6");
                row.put("权重编号为6的权重名称", wf6 != null && wf6.getQzmc() != null ? wf6.getQzmc() : "");
                row.put("权重编号为6的权重", weightMap.getOrDefault("6", 0.0));
                row.put("权重编号为6的权重得分", scoreMap.getOrDefault("6", 0));
                
                // 填充权重编号7的数据
                IndicatorsWf wf7 = weightInfoMap.get("7");
                row.put("权重编号为7的权重名称", wf7 != null && wf7.getQzmc() != null ? wf7.getQzmc() : "");
                row.put("权重编号为7的权重", weightMap.getOrDefault("7", 0.0));
                row.put("权重编号为7的权重得分", scoreMap.getOrDefault("7", 0));
                
                // 计算总分：权重编号为4的权重*权重编号为4的权重得分+权重编号为5的权重*权重编号为5的权重得分+权重编号为6的权重*权重编号为6的权重得分+权重编号为7的权重*权重编号为7的权重得分
                double totalScore = weightMap.getOrDefault("4", 0.0) * scoreMap.getOrDefault("4", 0)
                    + weightMap.getOrDefault("5", 0.0) * scoreMap.getOrDefault("5", 0)
                    + weightMap.getOrDefault("6", 0.0) * scoreMap.getOrDefault("6", 0)
                    + weightMap.getOrDefault("7", 0.0) * scoreMap.getOrDefault("7", 0);
                
                row.put("总分", totalScore);
                
                exportData.add(row);
            }
            
            if (!exportData.isEmpty()) {
                // 指定表头顺序
                List<String> headers = new ArrayList<>();
                headers.add("被测评部门编号");
                headers.add("被测评部门");
                headers.add("权重编号为4的权重名称");
                headers.add("权重编号为4的权重");
                headers.add("权重编号为4的权重得分");
                headers.add("权重编号为5的权重名称");
                headers.add("权重编号为5的权重");
                headers.add("权重编号为5的权重得分");
                headers.add("权重编号为6的权重名称");
                headers.add("权重编号为6的权重");
                headers.add("权重编号为6的权重得分");
                headers.add("权重编号为7的权重名称");
                headers.add("权重编号为7的权重");
                headers.add("权重编号为7的权重得分");
                headers.add("总分");
                
                ExcelUtil.exportExcel(response, "部门人事数据", exportData, headers);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 导出教师指标分数
     */
    @GetMapping("/export/teacher-indicator-scores")
    public void exportTeacherIndicatorScores(HttpServletResponse response) {
        try {
            List<TeacherIndicatorsScore> list = teacherIndicatorsScoreService.list(new QueryWrapper<TeacherIndicatorsScore>().orderByDesc("BH"));
            List<Map<String, Object>> exportData = new ArrayList<>();

            for (TeacherIndicatorsScore score : list) {
                Map<String, Object> map = new LinkedHashMap<>();
                
                // 获取教师信息 - 先尝试按教师编号查找，再尝试按教师姓名查找
                Teacher teacher = teacherService.getOne(new QueryWrapper<Teacher>().eq("JSBH", score.getBcpjs()));
                if (teacher == null) {
                    // 如果按编号找不到，尝试按姓名查找
                    teacher = teacherService.getOne(new QueryWrapper<Teacher>().eq("JSXM", score.getBcpjs()));
                }
                if (teacher == null) {
                    // 如果按姓名也找不到，尝试按工号查找
                    teacher = teacherService.getOne(new QueryWrapper<Teacher>().eq("JSGH", score.getBcpjs()));
                }
                
                // 按照要求的顺序和字段导出数据
                // 1. 教师编号
                if (teacher != null && teacher.getJsbh() != null) {
                    map.put("教师编号", String.valueOf(teacher.getJsbh()));
                } else {
                    map.put("教师编号", score.getBcpjs() != null ? score.getBcpjs() : "");
                }
                
                // 2. 教师工号
                if (teacher != null && teacher.getJsgh() != null) {
                    map.put("教师工号", teacher.getJsgh());
                } else {
                    map.put("教师工号", "");
                }
                
                // 3. 教师姓名
                if (teacher != null && teacher.getJsxm() != null) {
                    map.put("教师姓名", teacher.getJsxm());
                } else {
                    map.put("教师姓名", score.getBcpjs() != null ? score.getBcpjs() : "");
                }
                
                // 4. 指标编号
                map.put("指标编号", score.getCpzbbh() != null ? score.getCpzbbh() : "");
                
                // 5. 测评权重编号
                map.put("测评权重编号", score.getCpqzbh() != null ? score.getCpqzbh() : "");
                
                // 获取测评权重信息
                IndicatorsWf indicatorsWf = null;
                if (score.getCpqzbh() != null && !score.getCpqzbh().trim().isEmpty()) {
                    indicatorsWf = indicatorsWfService.getOne(new QueryWrapper<IndicatorsWf>().eq("QZBH", score.getCpqzbh()));
                }
                
                // 6. 测评权重名称
                if (indicatorsWf != null && indicatorsWf.getQzmc() != null) {
                    map.put("测评权重名称", indicatorsWf.getQzmc());
                } else {
                    map.put("测评权重名称", "");
                }
                
                // 7. 测评指标权重
                if (score.getCpzbqz() != null) {
                    map.put("测评指标权重", score.getCpzbqz());
                } else {
                    map.put("测评指标权重", "");
                }
                
                // 8. 分数
                if (score.getScore() != null) {
                    map.put("分数", score.getScore());
                } else {
                    map.put("分数", "");
                }

                exportData.add(map);
            }

            if (!exportData.isEmpty()) {
                // 指定表头顺序，确保导出Excel的列顺序正确
                List<String> headers = new ArrayList<>();
                headers.add("教师编号");
                headers.add("教师工号");
                headers.add("教师姓名");
                headers.add("指标编号");
                headers.add("测评权重编号");
                headers.add("测评权重名称");
                headers.add("测评指标权重");
                headers.add("分数");
                ExcelUtil.exportExcel(response, "教师指标分数", exportData, headers);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 导出教师行政数据
     */
    @GetMapping("/export/teacher-admin-data")
    public void exportTeacherAdminData(HttpServletResponse response) {
        try {
            // 查询所有教师指标分数
            List<TeacherIndicatorsScore> allScores = teacherIndicatorsScoreService.list(
                new QueryWrapper<TeacherIndicatorsScore>().orderByAsc("BCPJS", "CPQZBH")
            );
            
            // 按教师分组
            Map<String, List<TeacherIndicatorsScore>> teacherScoresMap = allScores.stream()
                .collect(Collectors.groupingBy(TeacherIndicatorsScore::getBcpjs));
            
            List<Map<String, Object>> exportData = new ArrayList<>();
            
            // 处理每个教师
            for (Map.Entry<String, List<TeacherIndicatorsScore>> entry : teacherScoresMap.entrySet()) {
                String teacherCode = entry.getKey();
                List<TeacherIndicatorsScore> scores = entry.getValue();
                
                // 获取教师信息 - 先尝试按教师编号查找（BCPJS可能是编号、姓名或工号）
                Teacher teacher = null;
                // 先尝试按编号查找
                try {
                    Integer teacherId = Integer.valueOf(teacherCode);
                    teacher = teacherService.getOne(new QueryWrapper<Teacher>().eq("JSBH", teacherId));
                } catch (NumberFormatException e) {
                    // 如果不是数字，继续尝试按姓名或工号查找
                }
                
                if (teacher == null) {
                    teacher = teacherService.getOne(new QueryWrapper<Teacher>().eq("JSXM", teacherCode));
                }
                if (teacher == null) {
                    teacher = teacherService.getOne(new QueryWrapper<Teacher>().eq("JSGH", teacherCode));
                }
                
                // 只处理行政类型(JSLX=0)的教师
                if (teacher == null || !"0".equals(teacher.getJslx())) {
                    continue;
                }
                
                // 创建导出数据行
                Map<String, Object> row = new LinkedHashMap<>();
                
                // 1. 被测评教师工号
                row.put("被测评教师工号", teacher.getJsgh() != null ? teacher.getJsgh() : "");
                
                // 2. 被测评教师
                row.put("被测评教师", teacher.getJsxm() != null ? teacher.getJsxm() : teacherCode);
                
                // 初始化各权重编号的数据
                Map<String, IndicatorsWf> weightInfoMap = new HashMap<>();
                Map<String, Double> weightMap = new HashMap<>();
                Map<String, List<Integer>> scoreListMap = new HashMap<>();
                
                // 遍历该教师的所有指标分数，按权重编号分组
                for (TeacherIndicatorsScore score : scores) {
                    String qzbh = score.getCpqzbh();
                    if (qzbh != null && (qzbh.equals("1") || qzbh.equals("2") || qzbh.equals("3"))) {
                        // 获取权重信息
                        if (!weightInfoMap.containsKey(qzbh)) {
                            IndicatorsWf indicatorsWf = indicatorsWfService.getOne(
                                new QueryWrapper<IndicatorsWf>().eq("QZBH", qzbh)
                            );
                            if (indicatorsWf != null) {
                                weightInfoMap.put(qzbh, indicatorsWf);
                                weightMap.put(qzbh, indicatorsWf.getQz() != null ? indicatorsWf.getQz() : 0.0);
                            } else {
                                // 如果找不到权重信息，使用分数记录中的权重
                                weightMap.put(qzbh, score.getCpzbqz() != null ? score.getCpzbqz() : 0.0);
                            }
                        }
                        // 收集分数（用于后续计算平均值）
                        if (score.getScore() != null) {
                            scoreListMap.computeIfAbsent(qzbh, k -> new ArrayList<>()).add(score.getScore());
                        }
                    }
                }
                
                // 计算每个权重编号的平均分数
                Map<String, Integer> scoreMap = new HashMap<>();
                for (Map.Entry<String, List<Integer>> scoreEntry : scoreListMap.entrySet()) {
                    String qzbh = scoreEntry.getKey();
                    List<Integer> scoreList = scoreEntry.getValue();
                    if (!scoreList.isEmpty()) {
                        double avgScore = scoreList.stream().mapToInt(Integer::intValue).average().orElse(0.0);
                        scoreMap.put(qzbh, (int) Math.round(avgScore));
                    }
                }
                
                // 填充权重编号1的数据
                IndicatorsWf wf1 = weightInfoMap.get("1");
                row.put("权重编号为1的权重名称", wf1 != null && wf1.getQzmc() != null ? wf1.getQzmc() : "");
                row.put("权重编号为1的权重", weightMap.getOrDefault("1", 0.0));
                row.put("权重编号为1的权重得分", scoreMap.getOrDefault("1", 0));
                
                // 填充权重编号2的数据
                IndicatorsWf wf2 = weightInfoMap.get("2");
                row.put("权重编号为2的权重名称", wf2 != null && wf2.getQzmc() != null ? wf2.getQzmc() : "");
                row.put("权重编号为2的权重", weightMap.getOrDefault("2", 0.0));
                row.put("权重编号为2的权重得分", scoreMap.getOrDefault("2", 0));
                
                // 填充权重编号3的数据
                IndicatorsWf wf3 = weightInfoMap.get("3");
                row.put("权重编号为3的权重名称", wf3 != null && wf3.getQzmc() != null ? wf3.getQzmc() : "");
                row.put("权重编号为3的权重", weightMap.getOrDefault("3", 0.0));
                row.put("权重编号为3的权重得分", scoreMap.getOrDefault("3", 0));
                
                // 计算总分：权重编号为1的权重*权重编号为1的权重得分+权重编号为2的权重*权重编号为2的权重得分+权重编号为3的权重*权重编号为3的权重得分
                double totalScore = weightMap.getOrDefault("1", 0.0) * scoreMap.getOrDefault("1", 0)
                    + weightMap.getOrDefault("2", 0.0) * scoreMap.getOrDefault("2", 0)
                    + weightMap.getOrDefault("3", 0.0) * scoreMap.getOrDefault("3", 0);
                
                row.put("总分", totalScore);
                
                exportData.add(row);
            }
            
            // 指定表头顺序
            List<String> headers = new ArrayList<>();
            headers.add("被测评教师工号");
            headers.add("被测评教师");
            headers.add("权重编号为1的权重名称");
            headers.add("权重编号为1的权重");
            headers.add("权重编号为1的权重得分");
            headers.add("权重编号为2的权重名称");
            headers.add("权重编号为2的权重");
            headers.add("权重编号为2的权重得分");
            headers.add("权重编号为3的权重名称");
            headers.add("权重编号为3的权重");
            headers.add("权重编号为3的权重得分");
            headers.add("总分");
            
            // 即使数据为空，也导出空文件（只有表头）
            if (exportData.isEmpty()) {
                // 创建一个空行，确保能导出表头
                Map<String, Object> emptyRow = new LinkedHashMap<>();
                for (String header : headers) {
                    emptyRow.put(header, "");
                }
                exportData.add(emptyRow);
            }
            
            ExcelUtil.exportExcel(response, "教师行政数据", exportData, headers);
        } catch (Exception e) {
            e.printStackTrace();
            try {
                response.setContentType("text/html;charset=UTF-8");
                response.getWriter().write("<script>alert('导出失败：" + e.getMessage() + "');</script>");
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }

    /**
     * 导出教师教师数据
     */
    @GetMapping("/export/teacher-teacher-data")
    public void exportTeacherTeacherData(HttpServletResponse response) {
        try {
            // 查询所有教师指标分数
            List<TeacherIndicatorsScore> allScores = teacherIndicatorsScoreService.list(
                new QueryWrapper<TeacherIndicatorsScore>().orderByAsc("BCPJS", "CPQZBH")
            );
            
            // 按教师分组
            Map<String, List<TeacherIndicatorsScore>> teacherScoresMap = allScores.stream()
                .collect(Collectors.groupingBy(TeacherIndicatorsScore::getBcpjs));
            
            List<Map<String, Object>> exportData = new ArrayList<>();
            
            // 处理每个教师
            for (Map.Entry<String, List<TeacherIndicatorsScore>> entry : teacherScoresMap.entrySet()) {
                String teacherCode = entry.getKey();
                List<TeacherIndicatorsScore> scores = entry.getValue();
                
                // 获取教师信息 - 先尝试按教师编号查找（BCPJS可能是编号、姓名或工号）
                Teacher teacher = null;
                // 先尝试按编号查找
                try {
                    Integer teacherId = Integer.valueOf(teacherCode);
                    teacher = teacherService.getOne(new QueryWrapper<Teacher>().eq("JSBH", teacherId));
                } catch (NumberFormatException e) {
                    // 如果不是数字，继续尝试按姓名或工号查找
                }
                
                if (teacher == null) {
                    teacher = teacherService.getOne(new QueryWrapper<Teacher>().eq("JSXM", teacherCode));
                }
                if (teacher == null) {
                    teacher = teacherService.getOne(new QueryWrapper<Teacher>().eq("JSGH", teacherCode));
                }
                
                // 只处理教师类型(JSLX=1)的教师
                if (teacher == null || !"1".equals(teacher.getJslx())) {
                    continue;
                }
                
                // 创建导出数据行
                Map<String, Object> row = new LinkedHashMap<>();
                
                // 1. 被测评教师工号
                row.put("被测评教师工号", teacher.getJsgh() != null ? teacher.getJsgh() : "");
                
                // 2. 被测评教师
                row.put("被测评教师", teacher.getJsxm() != null ? teacher.getJsxm() : teacherCode);
                
                // 初始化各权重编号的数据
                Map<String, IndicatorsWf> weightInfoMap = new HashMap<>();
                Map<String, Double> weightMap = new HashMap<>();
                Map<String, List<Integer>> scoreListMap = new HashMap<>();
                
                // 遍历该教师的所有指标分数，按权重编号分组
                for (TeacherIndicatorsScore score : scores) {
                    String qzbh = score.getCpqzbh();
                    if (qzbh != null && (qzbh.equals("1") || qzbh.equals("2") || qzbh.equals("3"))) {
                        // 获取权重信息
                        if (!weightInfoMap.containsKey(qzbh)) {
                            IndicatorsWf indicatorsWf = indicatorsWfService.getOne(
                                new QueryWrapper<IndicatorsWf>().eq("QZBH", qzbh)
                            );
                            if (indicatorsWf != null) {
                                weightInfoMap.put(qzbh, indicatorsWf);
                                weightMap.put(qzbh, indicatorsWf.getQz() != null ? indicatorsWf.getQz() : 0.0);
                            } else {
                                // 如果找不到权重信息，使用分数记录中的权重
                                weightMap.put(qzbh, score.getCpzbqz() != null ? score.getCpzbqz() : 0.0);
                            }
                        }
                        // 收集分数（用于后续计算平均值）
                        if (score.getScore() != null) {
                            scoreListMap.computeIfAbsent(qzbh, k -> new ArrayList<>()).add(score.getScore());
                        }
                    }
                }
                
                // 计算每个权重编号的平均分数
                Map<String, Integer> scoreMap = new HashMap<>();
                for (Map.Entry<String, List<Integer>> scoreEntry : scoreListMap.entrySet()) {
                    String qzbh = scoreEntry.getKey();
                    List<Integer> scoreList = scoreEntry.getValue();
                    if (!scoreList.isEmpty()) {
                        double avgScore = scoreList.stream().mapToInt(Integer::intValue).average().orElse(0.0);
                        scoreMap.put(qzbh, (int) Math.round(avgScore));
                    }
                }
                
                // 填充权重编号1的数据
                IndicatorsWf wf1 = weightInfoMap.get("1");
                row.put("权重编号为1的权重名称", wf1 != null && wf1.getQzmc() != null ? wf1.getQzmc() : "");
                row.put("权重编号为1的权重", weightMap.getOrDefault("1", 0.0));
                row.put("权重编号为1的权重得分", scoreMap.getOrDefault("1", 0));
                
                // 填充权重编号2的数据
                IndicatorsWf wf2 = weightInfoMap.get("2");
                row.put("权重编号为2的权重名称", wf2 != null && wf2.getQzmc() != null ? wf2.getQzmc() : "");
                row.put("权重编号为2的权重", weightMap.getOrDefault("2", 0.0));
                row.put("权重编号为2的权重得分", scoreMap.getOrDefault("2", 0));
                
                // 填充权重编号3的数据
                IndicatorsWf wf3 = weightInfoMap.get("3");
                row.put("权重编号为3的权重名称", wf3 != null && wf3.getQzmc() != null ? wf3.getQzmc() : "");
                row.put("权重编号为3的权重", weightMap.getOrDefault("3", 0.0));
                row.put("权重编号为3的权重得分", scoreMap.getOrDefault("3", 0));
                
                // 计算总分：权重编号为1的权重*权重编号为1的权重得分+权重编号为2的权重*权重编号为2的权重得分+权重编号为3的权重*权重编号为3的权重得分
                double totalScore = weightMap.getOrDefault("1", 0.0) * scoreMap.getOrDefault("1", 0)
                    + weightMap.getOrDefault("2", 0.0) * scoreMap.getOrDefault("2", 0)
                    + weightMap.getOrDefault("3", 0.0) * scoreMap.getOrDefault("3", 0);
                
                row.put("总分", totalScore);
                
                exportData.add(row);
            }
            
            // 指定表头顺序
            List<String> headers = new ArrayList<>();
            headers.add("被测评教师工号");
            headers.add("被测评教师");
            headers.add("权重编号为1的权重名称");
            headers.add("权重编号为1的权重");
            headers.add("权重编号为1的权重得分");
            headers.add("权重编号为2的权重名称");
            headers.add("权重编号为2的权重");
            headers.add("权重编号为2的权重得分");
            headers.add("权重编号为3的权重名称");
            headers.add("权重编号为3的权重");
            headers.add("权重编号为3的权重得分");
            headers.add("总分");
            
            // 即使数据为空，也导出空文件（只有表头）
            if (exportData.isEmpty()) {
                // 创建一个空行，确保能导出表头
                Map<String, Object> emptyRow = new LinkedHashMap<>();
                for (String header : headers) {
                    emptyRow.put(header, "");
                }
                exportData.add(emptyRow);
            }
            
            ExcelUtil.exportExcel(response, "教师教师数据", exportData, headers);
        } catch (Exception e) {
            e.printStackTrace();
            try {
                response.setContentType("text/html;charset=UTF-8");
                response.getWriter().write("<script>alert('导出失败：" + e.getMessage() + "');</script>");
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }

    /**
     * 导出教师总分
     */
    @GetMapping("/export/teacher-total-scores")
    public void exportTeacherTotalScores(HttpServletResponse response) {
        try {
            List<TeacherScore> list = teacherScoreService.list(new QueryWrapper<TeacherScore>().orderByDesc("SCORE"));
            List<Map<String, Object>> exportData = new ArrayList<>();

            for (TeacherScore score : list) {
                Map<String, Object> map = new HashMap<>();
                map.put("编号", score.getBh());
                map.put("教师编号", score.getBcpjs());
                map.put("总分", score.getScore());

                // 获取教师信息 - 先尝试按教师编号查找，再尝试按教师姓名查找
                Teacher teacher = teacherService.getOne(new QueryWrapper<Teacher>().eq("JSBH", score.getBcpjs()));
                if (teacher == null) {
                    // 如果按编号找不到，尝试按姓名查找
                    teacher = teacherService.getOne(new QueryWrapper<Teacher>().eq("JSXM", score.getBcpjs()));
                }
                if (teacher == null) {
                    // 如果按姓名也找不到，尝试按工号查找
                    teacher = teacherService.getOne(new QueryWrapper<Teacher>().eq("JSGH", score.getBcpjs()));
                }
                
                if (teacher != null) {
                    map.put("教师姓名", teacher.getJsxm());
                    map.put("部门编号", teacher.getBmbh());
                    
                    // 获取部门名称
                    Dept dept = deptService.getOne(new QueryWrapper<Dept>().eq("BMBH", teacher.getBmbh()));
                    map.put("部门名称", dept != null ? dept.getBmmc() : "");
                } else {
                    map.put("教师姓名", score.getBcpjs());
                    map.put("部门编号", "");
                    map.put("部门名称", "");
                }

                exportData.add(map);
            }

            if (!exportData.isEmpty()) {
                ExcelUtil.exportExcel(response, "教师总分", exportData);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 导出教师分数
     */
    @GetMapping("/teacher/export")
    public void exportTeacherScores(HttpServletResponse response) {
        try {
            List<TeacherScore> list = teacherScoreService.list(new QueryWrapper<TeacherScore>().orderByDesc("SCORE"));
            List<Map<String, Object>> exportData = new ArrayList<>();

            for (TeacherScore score : list) {
                Map<String, Object> map = new HashMap<>();
                map.put("编号", score.getBh());
                map.put("教师编号", score.getBcpjs());
                map.put("总分", score.getScore());

                Teacher teacher = teacherService.getOne(new QueryWrapper<Teacher>().eq("JSBH", Integer.valueOf(score.getBcpjs())));
                map.put("教师姓名", teacher != null ? teacher.getJsxm() : "");
                map.put("部门编号", teacher != null ? teacher.getBmbh() : "");

                exportData.add(map);
            }

            if (!exportData.isEmpty()) {
                ExcelUtil.exportExcel(response, "教师分数", exportData);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 分数统计查询
     */
    @GetMapping("/statistics")
    public Result<Map<String, Object>> getScoreStatistics(@RequestParam(required = false) String type,
                                     @RequestParam(required = false) String deptId) {
        try {
            Map<String, Object> statistics = new HashMap<>();

            if ("dept".equals(type)) {
                // 部门分数统计
                QueryWrapper<DeptScore> deptQuery = new QueryWrapper<>();
                if (deptId != null && !deptId.trim().isEmpty()) {
                    deptQuery.eq("BCPBM", deptId);
                }

                List<DeptScore> deptScores = deptScoreService.list(deptQuery);
                double deptAvg = deptScores.stream().mapToDouble(DeptScore::getScore).average().orElse(0.0);
                double deptMax = deptScores.stream().mapToDouble(DeptScore::getScore).max().orElse(0.0);
                double deptMin = deptScores.stream().mapToDouble(DeptScore::getScore).min().orElse(0.0);

                statistics.put("deptCount", deptScores.size());
                statistics.put("deptAvgScore", Math.round(deptAvg * 100.0) / 100.0);
                statistics.put("deptMaxScore", deptMax);
                statistics.put("deptMinScore", deptMin);
            } else {
                // 教师分数统计
                QueryWrapper<TeacherScore> teacherQuery = new QueryWrapper<>();
                List<TeacherScore> teacherScores = teacherScoreService.list(teacherQuery);
                double teacherAvg = teacherScores.stream().mapToDouble(TeacherScore::getScore).average().orElse(0.0);
                double teacherMax = teacherScores.stream().mapToDouble(TeacherScore::getScore).max().orElse(0.0);
                double teacherMin = teacherScores.stream().mapToDouble(TeacherScore::getScore).min().orElse(0.0);

                statistics.put("teacherCount", teacherScores.size());
                statistics.put("teacherAvgScore", Math.round(teacherAvg * 100.0) / 100.0);
                statistics.put("teacherMaxScore", teacherMax);
                statistics.put("teacherMinScore", teacherMin);
            }

            return Result.success(statistics);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取分数统计失败");
        }
    }

    // ===== 具体实现方法 =====

    /**
     * 部门指标分数计算
     */
    @PostMapping("/dept/calculate-indicators")
    public Result<String> calculateDeptIndicatorScores() {
        return this.calculateDeptIndicatorScoresInternal();
    }

    /**
     * 部门指标分数计算（前端调用的接口）
     */
    @PostMapping("/calculate-dept-indicator-scores")
    public Result<String> calculateDeptIndicatorScoresForFrontend() {
        return this.calculateDeptIndicatorScoresInternal();
    }

    /**
     * 部门指标分数计算内部实现
     */
    private Result<String> calculateDeptIndicatorScoresInternal() {
        try {
            deptIndicatorsScoreService.remove(new QueryWrapper<>());

            int count = 0;
            List<Dept> depts = deptService.list(new QueryWrapper<Dept>().eq("BMZT", "0"));
            List<Indicators> indicators = indicatorsService.list(new QueryWrapper<Indicators>().eq("KHFS", "1"));

            for (Dept dept : depts) {
                for (Indicators indicator : indicators) {
                    QueryWrapper<DeptEvaluatingRelation> relationQuery = new QueryWrapper<>();
                    relationQuery.eq("BCPBMBH", dept.getBmbh());
                    relationQuery.eq("CPZBBH", indicator.getZbbh());
                    relationQuery.eq("CPBS", "1");

                    List<DeptEvaluatingRelation> relations = deptRelationService.list(relationQuery);

                    if (!relations.isEmpty()) {
                        // 从relations中获取测评权重编号(cpqzbh)
                        String cpqzbh = relations.get(0).getCpqzbh(); // 取第一个关系记录的权重编号
                        
                        // 根据测评权重编号采用不同的去极值策略计算平均分
                        double avgScore = calculateAverageScoreWithOutlierRemoval(relations, cpqzbh);

                        DeptIndicatorsScore score = new DeptIndicatorsScore();
                        score.setBh(generateDeptIndicatorScoreId());
                        score.setBcpbm(dept.getBmbh());
                        score.setCpzbbh(indicator.getZbbh());
                        score.setCpzbqz(1.0);
                        score.setCpqzbh(cpqzbh); // 设置测评权重编号
                        score.setScore((int) Math.round(avgScore));

                        deptIndicatorsScoreService.save(score);
                        count++;
                    }
                }
            }

            return Result.success("部门指标分数计算完成，共计算 " + count + " 条记录");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("计算部门指标分数失败");
        }
    }

    /**
     * 部门总分计算（前端调用的接口）
     */
    @PostMapping("/calculate-dept-total-scores")
    public Result<String> calculateDeptTotalScoresForFrontend() {
        return this.calculateDeptTotalScoresInternal();
    }

    /**
     * 部门总分计算
     */
    @PostMapping("/dept/calculate-total")
    public Result<String> calculateDeptTotalScores() {
        return this.calculateDeptTotalScoresInternal();
    }

    /**
     * 部门总分计算内部实现
     */
    private Result<String> calculateDeptTotalScoresInternal() {
        try {
            deptScoreService.remove(new QueryWrapper<>());

            int count = 0;
            List<Dept> depts = deptService.list(new QueryWrapper<Dept>().eq("BMZT", "0"));

            for (Dept dept : depts) {
                QueryWrapper<DeptIndicatorsScore> scoreQuery = new QueryWrapper<>();
                scoreQuery.eq("BCPBM", dept.getBmbh());

                List<DeptIndicatorsScore> indicatorScores = deptIndicatorsScoreService.list(scoreQuery);

                if (!indicatorScores.isEmpty()) {
                    /*
                    double totalScore = indicatorScores.stream()
                            .filter(s -> s.getScore() != null)
                            .mapToInt(DeptIndicatorsScore::getScore)
                            .sum();
*/
                    double totalScore = indicatorScores.stream()
                            .filter(s -> s.getScore() != null && s.getCpzbqz() != null)
                            .mapToDouble(s -> s.getCpzbqz() * s.getScore())
                            .sum();

                    DeptScore score = new DeptScore();
                    score.setBh(generateDeptScoreId());
                    score.setBcpbm(dept.getBmbh());
                    score.setScore(totalScore);

                    deptScoreService.save(score);
                    count++;
                }
            }

            return Result.success("部门总分计算完成，共计算 " + count + " 条记录");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("计算部门总分失败");
        }
    }

    /**
     * 教师指标分数计算（前端调用的接口）
     */
    @PostMapping("/calculate-teacher-indicator-scores")
    public Result<String> calculateTeacherIndicatorScoresForFrontend() {
        return this.calculateTeacherIndicatorScoresInternal();
    }

    /**
     * 教师指标分数计算
     */
    @PostMapping("/teacher/calculate-indicators")
    public Result<String> calculateTeacherIndicatorScores() {
        return this.calculateTeacherIndicatorScoresInternal();
    }

    /**
     * 教师指标分数计算内部实现
     */
    private Result<String> calculateTeacherIndicatorScoresInternal() {
        try {
            teacherIndicatorsScoreService.remove(new QueryWrapper<>());

            int count = 0;
            List<Teacher> teachers = teacherService.list(new QueryWrapper<Teacher>().eq("JSZT", "0"));
            List<Indicators> indicators = indicatorsService.list(new QueryWrapper<Indicators>().eq("KHFS", "0"));

            for (Teacher teacher : teachers) {
                for (Indicators indicator : indicators) {
                    QueryWrapper<TeacherEvaluatingRelation> relationQuery = new QueryWrapper<>();
                    relationQuery.eq("BCPJSBH", String.valueOf(teacher.getJsbh()));
                    relationQuery.eq("CPZBBH", indicator.getZbbh());
                    relationQuery.eq("CPBS", "1");

                    List<TeacherEvaluatingRelation> relations = teacherRelationService.list(relationQuery);

                    if (!relations.isEmpty()) {
                        double avgScore = relations.stream()
                                .filter(r -> r.getTotalscore() != null && r.getTotalscore() > 0)
                                .mapToInt(TeacherEvaluatingRelation::getTotalscore)
                                .average()
                                .orElse(0.0);

                        // 从测评关系中获取测评权重编号
                        String cpqzbh = relations.get(0).getCpqzbh(); // 取第一个关系记录的权重编号

                        TeacherIndicatorsScore score = new TeacherIndicatorsScore();
                        score.setBh(generateTeacherIndicatorScoreId());
                        score.setBcpjs(String.valueOf(teacher.getJsbh()));
                        score.setCpzbbh(indicator.getZbbh());
                        score.setCpzbqz(1.0);
                        score.setCpqzbh(cpqzbh); // 设置测评权重编号
                        score.setScore((int) Math.round(avgScore));

                        teacherIndicatorsScoreService.save(score);
                        count++;
                    }
                }
            }

            return Result.success("教师指标分数计算完成，共计算 " + count + " 条记录");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("计算教师指标分数失败");
        }
    }

    /**
     * 教师总分计算（前端调用的接口）
     */
    @PostMapping("/calculate-teacher-total-scores")
    public Result<String> calculateTeacherTotalScoresForFrontend() {
        return this.calculateTeacherTotalScoresInternal();
    }

    /**
     * 教师总分计算
     */
    @PostMapping("/teacher/calculate-total")
    public Result<String> calculateTeacherTotalScores() {
        return this.calculateTeacherTotalScoresInternal();
    }

    /**
     * 教师总分计算内部实现
     */
    private Result<String> calculateTeacherTotalScoresInternal() {
        try {
            teacherScoreService.remove(new QueryWrapper<>());

            int count = 0;
            List<Teacher> teachers = teacherService.list(new QueryWrapper<Teacher>().eq("JSZT", "0"));

            for (Teacher teacher : teachers) {
                QueryWrapper<TeacherIndicatorsScore> scoreQuery = new QueryWrapper<>();
                scoreQuery.eq("BCPJS", String.valueOf(teacher.getJsbh()));

                List<TeacherIndicatorsScore> indicatorScores = teacherIndicatorsScoreService.list(scoreQuery);

                if (!indicatorScores.isEmpty()) {
                    /*
                    double totalScore = indicatorScores.stream()
                            .filter(s -> s.getScore() != null)
                            .mapToInt(TeacherIndicatorsScore::getScore)
                            .sum();
*/
                    double totalScore = indicatorScores.stream()
                            .filter(s -> s.getScore() != null && s.getCpzbqz() != null)
                            .mapToDouble(s -> s.getCpzbqz() * s.getScore())
                            .sum();

                    TeacherScore score = new TeacherScore();
                    score.setBh(generateTeacherScoreId());
                    score.setBcpjs(String.valueOf(teacher.getJsbh()));
                    score.setScore(totalScore);

                    teacherScoreService.save(score);
                    count++;
                }
            }

            return Result.success("教师总分计算完成，共计算 " + count + " 条记录");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("计算教师总分失败");
        }
    }

    /**
     * 重置部门分数
     */
    @PostMapping("/reset-dept-scores")
    public Result<String> resetDeptScores() {
        try {
            deptScoreService.remove(new QueryWrapper<>());
            deptIndicatorsScoreService.remove(new QueryWrapper<>());
            return Result.success("部门分数重置完成");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("重置部门分数失败");
        }
    }

    /**
     * 重置教师分数
     */
    @PostMapping("/reset-teacher-scores")
    public Result<String> resetTeacherScores() {
        try {
            teacherScoreService.remove(new QueryWrapper<>());
            teacherIndicatorsScoreService.remove(new QueryWrapper<>());
            return Result.success("教师分数重置完成");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("重置教师分数失败");
        }
    }

    /**
     * 测试教师指标分数计算 - 检查数据状态
     */
    @GetMapping("/test-teacher-calculation")
    public Result<Map<String, Object>> testTeacherCalculation() {
        try {
            // 检查教师数据
            List<Teacher> teachers = teacherService.list(new QueryWrapper<Teacher>().eq("JSZT", "0"));
            
            // 检查指标数据
            List<Indicators> indicators = indicatorsService.list(new QueryWrapper<Indicators>().eq("KHFS", "0"));
            
            // 检查测评关系数据
            QueryWrapper<TeacherEvaluatingRelation> relationQuery = new QueryWrapper<>();
            relationQuery.eq("CPBS", "1"); // 已测评
            List<TeacherEvaluatingRelation> completedRelations = teacherRelationService.list(relationQuery);
            
            // 检查有分数的测评关系
            QueryWrapper<TeacherEvaluatingRelation> scoreQuery = new QueryWrapper<>();
            scoreQuery.eq("CPBS", "1").isNotNull("TOTALSCORE").gt("TOTALSCORE", 0);
            List<TeacherEvaluatingRelation> relationsWithScores = teacherRelationService.list(scoreQuery);
            
            Map<String, Object> result = new HashMap<>();
            result.put("teacherCount", teachers.size());
            result.put("indicatorCount", indicators.size());
            result.put("completedRelationCount", completedRelations.size());
            result.put("relationsWithScoresCount", relationsWithScores.size());
            result.put("teachers", teachers.stream().limit(5).collect(Collectors.toList()));
            result.put("indicators", indicators);
            result.put("sampleRelations", relationsWithScores.stream().limit(3).collect(Collectors.toList()));
            
            return Result.success(result);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("检查教师数据失败: " + e.getMessage());
        }
    }

    /**
     * 测试部门指标分数计算 - 检查数据状态
     */
    @GetMapping("/test-dept-calculation")
    public Result<Map<String, Object>> testDeptCalculation() {
        try {
            // 检查部门数据
            List<Dept> depts = deptService.list(new QueryWrapper<Dept>().eq("BMZT", "0"));
            
            // 检查指标数据
            List<Indicators> indicators = indicatorsService.list(new QueryWrapper<Indicators>().eq("KHFS", "1"));
            
            // 检查测评关系数据
            QueryWrapper<DeptEvaluatingRelation> relationQuery = new QueryWrapper<>();
            relationQuery.eq("CPBS", "1"); // 已测评
            List<DeptEvaluatingRelation> completedRelations = deptRelationService.list(relationQuery);
            
            // 检查有分数的测评关系
            QueryWrapper<DeptEvaluatingRelation> scoreQuery = new QueryWrapper<>();
            scoreQuery.eq("CPBS", "1").isNotNull("TOTALSCORE").gt("TOTALSCORE", 0);
            List<DeptEvaluatingRelation> relationsWithScores = deptRelationService.list(scoreQuery);
            
            Map<String, Object> result = new HashMap<>();
            result.put("deptCount", depts.size());
            result.put("indicatorCount", indicators.size());
            result.put("completedRelationCount", completedRelations.size());
            result.put("relationsWithScoresCount", relationsWithScores.size());
            result.put("depts", depts.stream().limit(5).collect(Collectors.toList()));
            result.put("indicators", indicators);
            result.put("sampleRelations", relationsWithScores.stream().limit(3).collect(Collectors.toList()));
            
            return Result.success(result);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("检查数据失败: " + e.getMessage());
        }
    }

    // ===== ID生成方法 =====

    private Integer generateDeptIndicatorScoreId() {
        DeptIndicatorsScore maxRecord = deptIndicatorsScoreService.getOne(
                new QueryWrapper<DeptIndicatorsScore>().orderByDesc("BH").last("LIMIT 1"));
        return maxRecord != null ? maxRecord.getBh() + 1 : 1;
    }

    private Integer generateDeptScoreId() {
        DeptScore maxRecord = deptScoreService.getOne(
                new QueryWrapper<DeptScore>().orderByDesc("BH").last("LIMIT 1"));
        return maxRecord != null ? maxRecord.getBh() + 1 : 1;
    }

    private Integer generateTeacherIndicatorScoreId() {
        TeacherIndicatorsScore maxRecord = teacherIndicatorsScoreService.getOne(
                new QueryWrapper<TeacherIndicatorsScore>().orderByDesc("BH").last("LIMIT 1"));
        return maxRecord != null ? maxRecord.getBh() + 1 : 1;
    }

    private Integer generateTeacherScoreId() {
        TeacherScore maxRecord = teacherScoreService.getOne(
                new QueryWrapper<TeacherScore>().orderByDesc("BH").last("LIMIT 1"));
        return maxRecord != null ? maxRecord.getBh() + 1 : 1;
    }

    /**
     * 根据测评权重编号采用不同的去极值策略计算平均分
     * @param relations 部门测评关系列表
     * @param cpqzbh 测评权重编号
     * @return 去极值后的平均分
     */
    private double calculateAverageScoreWithOutlierRemoval(List<DeptEvaluatingRelation> relations, String cpqzbh) {
        // 获取所有有效分数
        List<Integer> scores = relations.stream()
                .filter(r -> r.getTotalscore() != null && r.getTotalscore() > 0)
                .map(DeptEvaluatingRelation::getTotalscore)
                .sorted()
                .collect(Collectors.toList());

        if (scores.isEmpty()) {
            return 0.0;
        }

        // 如果分数数量太少，直接计算平均值
        if (scores.size() <= 6) {
            return scores.stream().mapToInt(Integer::intValue).average().orElse(0.0);
        }

        int removeCount = 0;
        
        // 根据测评权重编号确定去极值策略
        if ("5".equals(cpqzbh)) {
            // 服务质量（cpqzbh=5）：去掉三个最高分和三个最低分
            removeCount = 3;
        } else if ("6".equals(cpqzbh)) {
            // 融合协作（cpqzbh=6）：去掉二个最高分和二个最低分
            removeCount = 2;
        } else {
            // 其他情况：不去极值，直接计算平均分
            return scores.stream().mapToInt(Integer::intValue).average().orElse(0.0);
        }

        // 确保去除的数量不超过总数量的一半
        int actualRemoveCount = Math.min(removeCount, scores.size() / 2);
        
        if (actualRemoveCount > 0 && scores.size() > actualRemoveCount * 2) {
            // 去掉最高分和最低分
            List<Integer> filteredScores = scores.subList(actualRemoveCount, scores.size() - actualRemoveCount);
            return filteredScores.stream().mapToInt(Integer::intValue).average().orElse(0.0);
        } else {
            // 如果去除后剩余分数太少，直接计算平均分
            return scores.stream().mapToInt(Integer::intValue).average().orElse(0.0);
        }
    }
}
